package cn.com.yangzhenyu.brick.util;

import cn.hutool.core.map.MapUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Created By 杨振宇
 * Date: 2019/1/25
 * Time: 15:51
 */
public class FreemarkerUtils {

    public static String templateString(String templateContent, Map<String, Object> dataMap) {
        Configuration cfg = new Configuration(Configuration.getVersion());
        try {
            StringTemplateLoader stringLoader = new StringTemplateLoader();
            stringLoader.putTemplate("sqlTemplate", templateContent);
            cfg.setTemplateLoader(stringLoader);
            Template template = cfg.getTemplate("sqlTemplate", "utf-8");
            StringWriter writer = new StringWriter();
            try {
                template.process(dataMap, writer);
                stringLoader.removeTemplate("sqlTemplate");
                return writer.toString();
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cfg.clone();
        }
        return null;
    }

    public static void main(String[] args) {
        String s = "adasdad${id}sadada";
        System.out.println(templateString(s, MapUtil.of("id","你是")));
    }

}
